package com.jzo2o.trade.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.jzo2o.common.constants.MqConstants;
import com.jzo2o.common.expcetions.MqException;
import com.jzo2o.rabbitmq.client.RabbitClient;
import com.jzo2o.trade.enums.TradingStateEnum;
import com.jzo2o.trade.mapper.TradingMapper;
import com.jzo2o.trade.model.domain.Trading;
import com.jzo2o.trade.service.IPaySuccessService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * \* User: chy
 * \* Date: 2025/10/8  17:47
 * \* Description:
 * \
 */
@Service
@Slf4j
public class PaySuccessServiceImpl implements IPaySuccessService {

    @Resource
    private TradingMapper tradingMapper;
    @Resource
    private RabbitTemplate rabbitTemplate;
    /**
     * 更新支付订单状态
     * @param tradingTradeNo
     */
    @Override
    public void updateTradingState(String tradingTradeNo ) {
        log.info("更新支付订单状态:{}", tradingTradeNo);
        // 1. 根据订单号查询订单
        Trading trading = tradingMapper.selectOne(Wrappers.<Trading>lambdaQuery()
                .eq(Trading::getTradingOrderNo, tradingTradeNo));
        if(trading == null){
            log.info("当前支付订单不存在:{}", tradingTradeNo);
        }

        // 2. 更新交易单状态
        trading.setTradingState(TradingStateEnum.YFK.getCode());
        // 设置交易号
//        trading.setTransactionId(transactionId);
        // 更新时间
        trading.setUpdateTime(LocalDateTime.now());
        tradingMapper.updateById(trading);

        // 3. 发送mq消息给订单服务,修改订单状态
        Map<String, Object> MsgMap = new HashMap<>();
        // 订单号
        MsgMap.put("productOrderNo", trading.getProductOrderNo());
        // 支付单号
        MsgMap.put("tradingTradeNo", trading.getTradingOrderNo());
        // 支付渠道
        MsgMap.put("tradingChannel", trading.getTradingChannel());
        rabbitTemplate.convertAndSend(MqConstants.Exchanges.TRADE,
                MqConstants.RoutingKeys.TRADE_UPDATE_STATUS,
                JSONUtil.toJsonStr(MsgMap));
    }
}
